package tpf.designer.pattern.course6.behavior_pattern1.homework.exercise1;

import java.sql.*;
import java.util.ArrayList;
import java.util.List;

abstract public class CommonDb<T extends Entity> {
    private static final String DRIVER_CLASS = "";
    private static final String DB_URL = "";
    private static final String USER = "";
    private static final String PASSWORD = "";

    public final List<T> populate(){
        List<T> results = new ArrayList<T>();
        Connection c = null;
        try {
            Class.forName(DRIVER_CLASS);
            c = DriverManager.getConnection(DB_URL, USER, PASSWORD);
            Statement stmt = c.createStatement();
            ResultSet rs = stmt.executeQuery(getSelectEntitySql());
            while (rs.next()) {
                T entities = createEntityFromResultSet(rs);
                results.add(entities);
            }
        } catch (ClassNotFoundException | SQLException e){
            throw new RuntimeException(e);
        } finally {
            try {
                c.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        return results;
    }

    protected abstract T createEntityFromResultSet(ResultSet rs) throws SQLException;

    protected abstract String getSelectEntitySql();
}
